package com.lovegu.thread.chat.connect;

//ServerConnectClientThread类

import com.lovegu.thread.chat.manage.ManageServerConnectClientThread;
import com.lovegu.thread.chat.message.Message;
import com.lovegu.thread.chat.message.MessageType;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

/**
 * 该类的一个对象和某个服务端保持通信
 * @author 86153
 */
public class ServerConnectClientThread extends Thread{

    private Socket socket;//该线程需要持有Socket保持通信
    private String userId;//连接到服务器端的用户Id

    public ServerConnectClientThread(Socket socket, String userId) {
        this.socket = socket;
        this.userId = userId;
    }

    @Override
    public void run() {//这里线程处于run状态，可以发送或接收到客户端消息
        while (true){
            try {
                System.out.println("服务器端和客户端"+ userId +"保持通信，读取数据");
                ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                Message ms = (Message)ois.readObject();
                //判断这个message类型，然后做相应的业务处理
                if (ms.getMesType().equals(MessageType.MESSAGE_GET_ONLINE_FRIEND)){
                    //客户端要在线用户列表
                    //在线用户列表格式 100 200 紫霞仙子
                    System.out.println(ms.getSender() + " 要在线用户列表");
                    String onlineUser = ManageServerConnectClientThread.getOnlineUser();
                    //返回message
                    Message message2 = new Message();
                    message2.setMesType(MessageType.MESSAGE_RET_ONLINE_FRIEND);
                    message2.setContent(onlineUser);
                    message2.setGetter(ms.getGetter());
                    //返回给客户端
                    ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
                    oos.writeObject(message2);

                }else {
                    System.out.println("其他的处理");
                }
                //
                if (ms.getMesType().equals(MessageType.MESSAGE_CLIENT_EXIT)){
                    System.out.println(ms.getSender() + " 退出系统");
                    //将对应的线程从线程集合移除
                    ManageServerConnectClientThread.removeServerConnectClientThread(ms.getSender());
                    socket.close();//关闭连接
                    break;//退出线程
                }
            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    }
}